﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;


namespace Util.Props
{
    
    /// <summary>
    /// Loads configuration from an XML file
    /// </summary>
    public class SaxLoader
    {
        private String url = null;
        private Dictionary<String, RawPropertyData> rpdMap = null;
        private Dictionary<String, String> globalProperties = null;
        private Boolean replaceDuplicates = false;

        /// <summary>
        /// Creates a loader that will load from the given location 
        /// </summary>
        /// <param name="url">the location to load</param>
        /// <param name="globalProperties">the map of global properties</param>
        /// <param name="initRPD"></param>
        /// <param name="replaceDuplicates"></param>
        public SaxLoader(String url, Dictionary<String, String> globalProperties, Dictionary<String, RawPropertyData> initRPD, Boolean replaceDuplicates)
        {
            this.url = url;
            this.globalProperties = globalProperties;
            this.replaceDuplicates = replaceDuplicates;
            this.rpdMap = initRPD == null ? new Dictionary<String, RawPropertyData>() : initRPD;
        }

        /// <summary>
        /// Creates a loader that will load from the given location 
        /// </summary>
        /// <param name="url">the location to load</param>
        /// <param name="globalProperties">the map of global properties</param>
        public SaxLoader(String url, Dictionary<String, String> globalProperties)
            : this(url, globalProperties, null, false)
        {

        }

        /// <summary>
        /// Loads a set of configuration data from the location 
        /// </summary>
        /// <returns>a map keyed by component name containing RawPropertyData objects</returns>
        public Dictionary<String, RawPropertyData> load()
        {
            try
            {
                //SAXParserFactory factory = SAXParserFactory.newInstance();
                //XMLReader xr = factory.newSAXParser().getXMLReader();
                SaxXmlReader xr = new  SaxXmlReader();
                ConfigHandler handler = new ConfigHandler(rpdMap, globalProperties, replaceDuplicates, url);
                xr.setContentHandler(handler);
                xr.parse(url);
            }
            catch (XmlException e)
            {
                String msg = "Error while parsing line " + e.LineNumber + " of " + url + ": " + e.Message;
                throw new IOException(msg);
            }
            catch (IOException e)
            {
                throw new IOException("Problem with XML: " + e);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return rpdMap;
        }
    }
}
